package library;

import java.util.Vector;

import javax.swing.table.DefaultTableModel;

public class LendingModel
extends DefaultTableModel
{
	private static final long serialVersionUID = -7062399880170740723L;
	
	private String[] colNames = {"Buch", "Student"};	
	private Vector<String[]> data = null;
	
	public LendingModel(Vector<Lending> v)
	{
		super.setColumnIdentifiers(colNames);
		data = new Vector<String[]>(20);
		
		for (int i = 0; i < v.size(); ++i)
		{
			data.add(getData(v.elementAt(i).getBook(), v.elementAt(i).getStudent()));
			super.addRow(getRowData(data.elementAt(i)));
		}
	}
	
	private String[] getRowData(String[] in)
	{
		return new String[]{in[0], in[2]};
	}
	
	private String[] getData(Book b, Student s)
	{
		String [] str = new String[4];
		//str[0] = Integer.toString(b.getId());
		//str[1] =  Integer.toString(s.getId());
		str[0] = b.getTitle();
		str[1] = Integer.toString(b.getId());
		str[2] = s.getName();
		str[3] = Integer.toString(s.getId());
		
		return str;
	}
	
	public void add(Lending l)
	{
		data.add(getData(l.getBook(), l.getStudent()));
		super.addRow(getRowData(data.lastElement()));
	}
	
	public void reBuild(Vector<Lending> v)
	{
		super.setNumRows(0);
		data.clear();
		
		for (int i = 0; i < v.size(); ++i)
		{
			data.add(getData(v.elementAt(i).getBook(), v.elementAt(i).getStudent()));
			super.addRow(getRowData(data.elementAt(i)));
		}
	}

	@Override
	public boolean isCellEditable(int row, int column)
	{
		return false;
	}
	
	public int getLendingBookId(int idx)
	{
		return Integer.parseInt(data.elementAt(idx)[1]);
	}

	public int getLendingStudentId(int idx)
	{
		return Integer.parseInt(data.elementAt(idx)[3]);
	}
}
